// 组件加载器
const ComponentLoader = {
    // 已加载的组件缓存
    loadedComponents: new Map(),

    /**
     * 加载HTML组件
     * @param {string} componentPath - 组件路径
     * @param {string} targetSelector - 目标容器选择器
     * @returns {Promise<void>}
     */
    async loadComponent(componentPath, targetSelector) {
        try {
            // 检查缓存
            if (this.loadedComponents.has(componentPath)) {
                const targetElement = document.querySelector(targetSelector);
                if (targetElement) {
                    targetElement.innerHTML = this.loadedComponents.get(componentPath);
                }
                return;
            }

            // 加载组件
            const response = await fetch(componentPath);
            if (!response.ok) {
                throw new Error(`Failed to load component: ${componentPath}`);
            }

            const html = await response.text();
            
            // 缓存组件
            this.loadedComponents.set(componentPath, html);

            // 插入到目标容器
            const targetElement = document.querySelector(targetSelector);
            if (targetElement) {
                targetElement.innerHTML = html;
            }
        } catch (error) {
            console.error('Error loading component:', error);
        }
    },

    /**
     * 加载多个组件
     * @param {Array<{path: string, target: string}>} components - 组件配置数组
     * @returns {Promise<void>}
     */
    async loadComponents(components) {
        const promises = components.map(component => 
            this.loadComponent(component.path, component.target)
        );
        await Promise.all(promises);
    },

    /**
     * 清除组件缓存
     */
    clearCache() {
        this.loadedComponents.clear();
    }
}; 